<template>
  <div class="followAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div
      class="search-button"
      v-if="pageType !== 'detail' && pageType !== 'check'"
    >
      <el-button
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="btn save"
        @click="handleAddSave(followFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >分配</el-button
      >
      <el-button class="btn back" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <div class="task transform-down">
      <div class="task-item task-current">
        {{ followForm.maintanceTaskName }}({{ taskType }})
      </div>
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">任务信息</span>
        </template>
        <div class="follow-info">
          <el-form
            :model="followForm"
            ref="followFormRef"
            :rules="queryRules"
            label-width="120px"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <!-- <el-col :span="6">
                <el-form-item label="选择部门：" prop="deptId">
                  <el-select
                    ref="refSelect"
                    v-model="followForm.deptId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleDepart"
                  >
                    <el-option
                      v-for="dict in deptList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="选择工程师：" prop="allotRelList">
                  <el-select
                  filterable
                    style="height: 100%"
                    v-model="followForm.allotRelList"
                    multiple
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleAllotRelChange"
                  >
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">人员姓名</span>
                      <span style="margin: 0 80px 0 50px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </el-option>
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userId"
                    >
                      <span
                        style="display: inline-block; width: 80px; float: left"
                        >{{ item.nickName }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 15px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        >{{ item.phonenumber ? item.phonenumber : "--" }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          font-size: 13px;
                          margin: 0 0px 0 0px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.postName ? item.postName : "--" }}
                      </span>
                      <span
                        style="
                          display: inline-block;
                          margin: 0 0px 0 0px;
                          font-size: 13px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.fullDeptName ? item.fullDeptName : "--" }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="计划开始时间：" prop="startTime">
                  <el-date-picker
                    value-format="YYYY-MM-DD HH:mm:ss"
                    v-model="followForm.startTime"
                    class="search-input"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="计划结束时间：" prop="endTime">
                  <el-date-picker
                    value-format="YYYY-MM-DD HH:mm:ss"
                    v-model="followForm.endTime"
                    class="search-input"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：" prop="remark">
                  <el-input
                    maxlength="2000"
                    style="width: 100%"
                    v-model="followForm.remark"
                    type="textarea"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 跟进记录 -->
      <el-collapse-item name="2">
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">工程师名下现存任务</span>
        </template>
        <div
          class="task transform-down"
          style="margin-top: 20px"
          v-if="followForm.allotRelList.length"
        >
          <div
            class="task-item"
            :class="currentUser === item ? 'task-current' : ''"
            v-for="(item, index) in followForm.allotRelList"
            :key="index"
            @click="handleUserTask(item)"
          >
            {{ getNameById(item) }}
          </div>
        </div>
        <div class="task-number" v-if="followForm.allotRelList.length">
          名下现存项目数量：{{ followForm.tableData.length }}
        </div>
        <div class="follow-detail-info">
          <!-- 表格数据 -->
          <el-table
            :data="followForm.tableData"
            border
            height="100%"
            :header-cell-style="{ background: 'red' }"
          >
            <el-table-column
              label="项目名称"
              prop="projectName"
              :show-overflow-tooltip="true"
              min-width="120"
              align="center"
            />
            <el-table-column
              label="项目任务"
              prop="taskName"
              :show-overflow-tooltip="true"
              min-width="120"
              align="center"
            />
            <el-table-column
              label="开始时间"
              prop="beginTime"
              :show-overflow-tooltip="true"
              min-width="140"
              align="center"
            /><el-table-column
              label="结束时间"
              prop="endTime"
              :show-overflow-tooltip="true"
              min-width="140"
              align="center"
            /><el-table-column
              label="距离任务开始天数"
              prop="startTimeNum"
              :show-overflow-tooltip="true"
              min-width="180"
              align="center"
            /><el-table-column
              label="距离任务结束天数"
              prop="endTimeNum"
              :show-overflow-tooltip="true"
              min-width="180"
              align="center"
            /><el-table-column
              label="任务状态"
              prop="taskStatus"
              :show-overflow-tooltip="true"
              min-width="160"
              align="center"
            />
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import {
  getEndFollowApi,
  addFollowApi,
  getProjectApi,
} from "@/api/sales/project";
// getUserListApi,
import { getDeptListApi } from "@/api/information/customer";
import {
  getUserListApi,
  workAllotApi,
  getUserTaskApi,
} from "@/api/operation/work";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
  // 更新跟进组件显隐
  "update:followAddShow",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const followFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
const currentUser = ref(null);
const taskType = ref("");
// 跟进表单引用
const followFormTemplate = {
  allotRelList: [],
  endTime: "",
  maintanceTaskName: "",
  remark: "",
  startTime: "",
  workOrderId: null,
  deptId: null,
  tableData: [],
};
const data = reactive({
  // 跟进表单
  followForm: JSON.parse(JSON.stringify(followFormTemplate)),
  // 跟进表单校验规则
  queryRules: {
    allotRelList: [
      { required: true, message: "请选择工程师", trigger: "change" },
    ],
    startTime: [
      { required: true, message: "请选择计划开始时间", trigger: "change" },
    ],
    endTime: [
      { required: true, message: "请选择计划结束时间", trigger: "change" },
    ],
  },
  // 用户列表
  userList: [],
  // 部门列表
  deptList: [],
});
const { followForm, queryRules, userList, deptList } = toRefs(data);

/**
 * @description: 保存
 * @param {Object} followFormRef 跟进表单引用
 */
const handleAddSave = async (followFormRef) => {
  if (!followFormRef) return;
  await followFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          const res = await workAllotApi(followForm.value);
          if (res.code === 200) {
            emit("update:followAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 匹配工程师名称
 */
const getNameById = (id) => {
  const foundItem = userList.value.find((item) => item.userId === id);
  return foundItem ? foundItem.nickName : "未知";
};

/**
 * @description: 获取用户名下任务
 */
const handleUserTask = async (userId) => {
  currentUser.value = userId;
  const res = await getUserTaskApi(userId);
  followForm.value.tableData = [
    ...(res.mainTaskListVoList || []),
    ...(res.proTaskListVos || []),
  ];
};

/**
 * @description: 工程师变更
 */
const handleAllotRelChange = async (userId) => {
  if (
    !followForm.value.allotRelList.some((item) => currentUser.value === item)
  ) {
    followForm.value.tableData = [];
    currentUser.value = null;
  }
};

/**
 * @description: 返回
 */
const handleBack = () => {
  ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      emit("update:followAddShow", false);
      followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
    })
    .catch(() => {});
};

/**
 * @description: 处理部门选择
 * @param {Number} value 当前值followForm.value.deptId改成null
 */
const handleDepart = async (value) => {
  followForm.value.allotRelList = [];
  if (value) {
    await getUserListApi(null).then((res) => {
      if (res) {
        userList.value = res;
      }
    });
  } else {
    userList.value = [];
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (row) => {
  const id = row.workOrderId;
  taskType.value = row.constructionStatusName;
  followForm.value.startTime = row.desireStartTime;
  followForm.value.endTime = row.desireEndTime;
  followForm.value.workOrderId = row.workOrderId;
  followForm.value.maintanceTaskName = row.workOrderName;
  try {
    followForm.value.projectId = id;
    if (props.pageType === "follow") {
      const res = await getEndFollowApi(id);
      if (res) {
        followForm.value.lastTime = res.createTime;
      }
    } else {
      const res = await getProjectApi(id);
    }
  } catch (error) {}
};

/**
 * @description: 销售部门列表2改成null值
 */
const getDeptList = async () => {
  await getUserListApi(null).then((res) => {
    if (res) {
      userList.value = res;
    }
  });
};

onMounted(() => {
  getDeptList();
  if (props.pageType !== "detail" && props.pageType !== "check") {
    nextTick(() => {
      setTimeout(() => {
        refInput.value.focus();
      }, 800);
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.followAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .follow-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .follow-detail-info {
    margin-top: 20px;
  }
  // .task {
  //   width: 100%;
  //   height: 50px;
  //   margin-bottom: 20px;
  //   &-item {
  //     background-color: #dee6ed;
  //     width: 170px;
  //     height: 50px;
  //     line-height: 50px;
  //     text-align: center;
  //     cursor: pointer;
  //     &:hover {
  //       background: #007cef;
  //       color: #fff;
  //     }
  //     background: #007cef;
  //     color: #fff;
  //   }
  // }
  .task {
    width: 1360px;
    height: 56px;
    margin-bottom: 20px;
    display: flex;
    overflow-x: auto;
    &-item {
      background-color: #dee6ed;
      min-width: 220px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      margin-right: 2px;
      cursor: pointer;
      &:hover {
        // background: #007cef;
        // color: #fff;
      }
      background: #dee6ed;
      color: #333333;
    }
    .task-current {
      background: #007cef;
      color: #fff;
    }
  }
  .people {
    margin-top: 10px;
    &-item {
      margin-right: 10px;
      cursor: pointer;
      text-decoration: underline;
      &:hover {
        color: #007cef;
      }
    }
  }
  .task-number {
    margin-top: -20px;
    font-size: 16px;
  }
}
</style>
